<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable>
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userlist">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="handleSwitchChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteManager(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                @click="showRoleDailog(scope.row)"
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog title="提示" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
      <!-- 表单区域 -->
      <el-form :rules="AddUserFormRules" :model="addUser" ref="AddUserFormRef" label-width="70px">
        <!-- 用户名 -->
        <el-form-item prop="username" label="用户名:">
          <el-input v-model="addUser.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password" label="密码:">
          <el-input type="password" v-model="addUser.password"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item prop="email" label="邮箱:">
          <el-input v-model="addUser.email"></el-input>
        </el-form-item>
        <!-- 手机 -->
        <el-form-item prop="mobile" label="手机:">
          <el-input v-model="addUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addManager">确 定</el-button>
      </span>
    </el-dialog>
    <!-- ========================================================= -->
    <!-- ========================================================= -->
    <!-- 修改用户信息的对话框 -->
    <el-dialog title="提示" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
      <!-- 表单区域 -->
      <el-form
        :rules="editUserFormRules"
        :model="editUser"
        ref="editUserFormRef"
        label-width="70px"
      >
        <!-- 用户名 -->
        <el-form-item prop="username" label="用户名:">
          <el-input :disabled="true" v-model="editUser.username"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item prop="email" label="邮箱:">
          <el-input v-model="editUser.email"></el-input>
        </el-form-item>
        <!-- 手机 -->
        <el-form-item prop="mobile" label="手机:">
          <el-input v-model="editUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editManager">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色的弹窗 -->
    <el-dialog title="提示" :visible.sync="SettingRoleDialogVisible" width="50%">
      <div>
        <p>姓名：{{ userInfo.username }}</p>
        <p>角色：{{ userInfo.role_name }}</p>
        <div>
          <span>分配角色 :</span>
          &nbsp;&nbsp;
          <el-select v-model="selectedRole" placeholder="请选择">
            <el-option
              v-for="item in rolelist"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="SettingRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="SettingRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 定义几个函数内的成员
    // cb是什么？
    // emailRule只是一个变量 这个变量就是一个函数
    // 函数接收了3个参数
    // 我们声明的emailRule函数由谁调用？？由elementui中的form组件调用
    var emailRule = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };

    var mobileRule = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };

    return {
      queryInfo: {
        query: "", //该字段就是用来做查询功能的
        pagenum: 1,
        pagesize: 2
      },
      userlist: [],
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      SettingRoleDialogVisible: false,
      addUser: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      editUser: {
        id: "",
        username: "",
        email: "",
        mobile: ""
      },
      AddUserFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入电子邮箱", trigger: "blur" },
          {
            validator: emailRule,
            trigger: "blur"
          }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: mobileRule, trigger: "blur" }
        ]
      },
      editUserFormRules: {
        email: [
          { required: true, message: "请输入电子邮箱", trigger: "blur" },
          {
            validator: emailRule,
            trigger: "blur"
          }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: mobileRule, trigger: "blur" }
        ]
      },
      userInfo: {},
      rolelist: [],
      selectedRole: ""
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败！");
      }
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    handleSizeChange(newsize) {
      console.log(newsize);
      this.queryInfo.pagesize = newsize;
      this.getUserList();
    },
    handleCurrentChange(newnum) {
      console.log(newnum);
      this.queryInfo.pagenum = newnum;
      this.getUserList();
    },
    async handleSwitchChange(info) {
      const { data: res } = await this.$http.put(
        `users/${info.id}/state/${info.mg_state}`
      );
      if (res.meta.status !== 200) {
        info.mg_state = !info.mg_state;
        return this.$message.error("更新用户状态失败！");
      }
      this.$message.success("更新用户状态成功！");
    },
    addDialogClose() {
      this.$refs.AddUserFormRef.resetFields();
      // console.log(this.$refs)
    },
    editDialogClose() {
      this.$refs.editUserFormRef.resetFields();
    },
    // 新增用户
    async addManager() {
      const { data: res } = await this.$http.post("users", this.addUser);

      if (res.meta.status != 201) {
        return this.$message.error("添加失败");
      }
      this.$message.success("成功");
      // 关闭窗口
      this.addDialogVisible = false;
      // 重新获取列表数据
      this.getUserList();
    },
    // 修改用户
    editManager() {
      console.log("发起修改请求");
      this.$http
        .put(`users/${this.editUser.id}`, {
          email: this.editUser.email,
          mobile: this.editUser.mobile
        })
        .then(res => {
          // console.log(res.data.data);
          if (res.data.meta.status != 200) {
            return this.$message.error("修改失败");
          }
          this.$message.success("修改成功");
          this.editDialogVisible = false;
          this.getUserList();
        });
    },
    showEditDialog(userinfo) {
      this.editDialogVisible = true;
      this.editUser.id = userinfo.id;
      this.editUser.username = userinfo.username;
      this.editUser.email = userinfo.email;
      this.editUser.mobile = userinfo.mobile;
    },

    async deleteManager(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (confirmResult == "cancel") {
        return this.$message.info("取消了删除");
      }
      // 如果点击的是确定那么就要发送请求了
      const { data: res } = await this.$http.delete("users/" + id);
      if (res.meta.status != 200) {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      this.getUserList();
    },

    // 展示分配角色弹窗
    async showRoleDailog(userinfo) {
      console.log(userinfo);
      this.userInfo = userinfo;
      this.SettingRoleDialogVisible = true;
      // 发起请求获取所有的角色列表
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status != 200) {
        return false;
      }
      this.rolelist = res.data;
    },
    async SettingRole(){
      const { data:res } = await this.$http.put(`users/${this.userInfo.id}/role`,{ rid:this.selectedRole })
      if(res.meta.status!=200){
        return this.$message.error('更新角色失败')
      }
      this.$message.success('成功')
      this.SettingRoleDialogVisible = false
      this.getUserList()
    }
  }
};
</script>

<style lang="less" scoped>
</style>

